//
//  GenericVerifySMSViewController.m
//  HuLaQuan
//
//  Created by hok on 1/20/16.
//  Copyright © 2016 Jianghao. All rights reserved.
//

#import "GenericVerifySMSViewController.h"

#import "YuVerifyButton.h"

#import "YuLoginInputInfoField.h"

#import "CurrentUser.h"


@interface GenericVerifySMSViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet YuVerifyButton *verifyCodeButton;
@property (weak, nonatomic) IBOutlet UIButton *nextButton;

@property (weak, nonatomic) IBOutlet YuLoginInputInfoField *verifyCodeField;
@property (strong, nonatomic) NSTimer *timerForVeirify;


//请输入短信验证码
@property (weak, nonatomic) IBOutlet UILabel *phoneNumberLabel;

@end

@implementation GenericVerifySMSViewController

static int timerCount;

- (NSMutableDictionary *)userInfo
{
    if (!_userInfo) {
        _userInfo = [[NSMutableDictionary alloc] init];
    }
    return _userInfo;
}

- (SMSVerifyEngine *)smsVerifyEngine
{
    if (!_smsVerifyEngine) {
        _smsVerifyEngine = [[SMSVerifyEngine alloc] init];
    }
    return _smsVerifyEngine;
}
#pragma mark - Setup
- (void)setupUI
{
    self.title = @"忘记密码";
    
    [self setupNavBackButton];
    
    [self setupTextField];
    
    // 加手势处理键盘
    [self setupTapGesture];
    
    self.nextButton.enabled = NO;
    
    self.verifyCodeField.layer.borderWidth = 0;
    
    [self setupSMSEngineType];
}

- (void)setupTextField
{
    [self.verifyCodeField setColorfulPlaceholder:kverifyFiledPlaceholder];
}

#pragma mark - Call Back
- (void)getSMSVeriCodeFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        [self getSMSFinish:messageDic];
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}
- (void)verifySMSVeriCodeFinish:(NSNotification*) notification
{
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        NSLog(@"--- verify sms finish%@",messageDic[@"result"]);
        [self verifySMSFinish:messageDic[@"result"]];
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}
#pragma mark - Controller Life Cycle
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getSMSVeriCodeFinish:) name:@"GetSMSVeriCodeFinish" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(verifySMSVeriCodeFinish:) name:@"VerifySMSVeriCodeFinish" object:nil];
    
    
    self.phoneNumberLabel.text = [NSString stringWithFormat:@"请输入%@短信验证码",self.userInfo[@"userName"] ? self.userInfo[@"userName"] : [CurrentUser sharedInstance].name];
}

- (void)viewWillDisappear:(BOOL)animated
{
     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetSMSVeriCodeFinish" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"VerifySMSVeriCodeFinish" object:nil];
    [self.timerForVeirify invalidate];
    [super viewWillDisappear:YES];
    
}
- (void)getSMSFinish:(id)message
{
    
}
- (void)setupSMSEngineType
{
    
}
/**
 *  Need To Overwrite
 *  Call Back Of Verify SMS Finish
 *
 *  @param message tokenValue:验证手机后的临时Token； tokenTime: Token有效次数
 */
- (void)verifySMSFinish:(id)message
{
    
}
- (IBAction)tapNextButton:(id)sender {
    if (self.verifyCodeField.text && self.verifyCodeField.text.length == 6) {
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.smsVerifyEngine verifySMSWithcode:self.verifyCodeField.text];
    }
    
}
/**
 *  Get Verify Code Button
 *
 *  @param sender <#sender description#>
 */
- (IBAction)tapVerifyCodeButton:(id)sender {
    NSLog(@"%@",self.userInfo);
    
    [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
    [self.smsVerifyEngine getSMSWithMobile:self.userInfo[@"userName"] ? self.userInfo[@"userName"] : [CurrentUser sharedInstance].name];
    [self beginTimerForVerify];
}
#pragma mark - Timer
- (void)beginTimerForVerify
{
    timerCount = 60;
    self.timerForVeirify = [NSTimer scheduledTimerWithTimeInterval:1
                                                            target:self
                                                          selector:@selector(timerForVeirify:)
                                                          userInfo:nil
                                                           repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timerForVeirify
                                 forMode:NSRunLoopCommonModes];
    self.verifyCodeButton.enabled = NO;
}

- (void)timerForVeirify:(NSTimer *)timer
{
    [self.verifyCodeButton setTitle:[NSString stringWithFormat:@"%d秒后点击",timerCount] forState:UIControlStateNormal];
    if (timerCount == 0) {
        [self resetVerifyButton:self.verifyCodeButton];
        [timer invalidate];
    }
    timerCount--;
    
    
}
- (void)resetVerifyButton:(UIButton *)button
{
    button.enabled = YES;
    [button setTitle:@"获取验证码" forState:UIControlStateNormal];
}

#pragma mark - Textfield delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    YuLoginInputInfoField *textF = (YuLoginInputInfoField *)textField;
    [textF setColorfulPlaceholder:@""];
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.text.length == 0 ) {
        YuLoginInputInfoField *textF = (YuLoginInputInfoField *)textField;
        [textF setColorfulPlaceholder:kverifyFiledPlaceholder];
        
    }
    if (self.verifyCodeField.text.length == 0) {
        self.nextButton.enabled = NO;
    }
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if ( self.verifyCodeField.text.length > 0) {
        self.nextButton.enabled = YES;
    }
    return YES;
    
    // return [self validateNumber:string];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
